//
//  Utilis.m
//  OnionHome
//
//  Created by fengjie on 2019/9/27.
//  Copyright © 2019 FengJie. All rights reserved.
//

#import "Utilis.h"
#import "VideoPlayModel.h"


@implementation Utilis

/**
 获取一个随机整数 范围在[from,to] 包括from，包括to
 
 @param from 起始数
 @param to 结束数
 @return 返回
 */
+(NSInteger)getRandomNumber:(NSInteger)from to:(NSInteger)to
{
    return (NSInteger)(from + (arc4random() % (to - from + 1)));
}

/// 随机获取用户头像
+(UIImage *)getRandomUserImage{
    NSInteger  count = [Utilis getRandomNumber:1 to:40];
    NSString * userimage =  [NSString stringWithFormat:@"user%ld",(long)count];
//    DLog(@"用户头像角标%ld",(long)count);

    return IMAGE_NAMED(userimage);

}

/// 随机获取动态图片
+(NSString *)getRandomDynamicImage{
    NSInteger  count = [Utilis getRandomNumber:1 to:38];
//    DLog(@"照片角标%ld",(long)count);
    NSString * userimage =  [NSString stringWithFormat:@"dynamic%ld",(long)count];
    
    return userimage;

}

/// 判断当前设备是否是模拟器
+(BOOL)isSimuLator{
    if (TARGET_IPHONE_SIMULATOR == 1 && TARGET_OS_IPHONE == 1) {
        //模拟器
        return YES;
    }else{
        //真机
        return NO;
    }
}
+(NSMutableArray *)getVideos{
    NSMutableArray * videoArray = [NSMutableArray array];
    
    // 获得全部相片
    PHFetchResult<PHAssetCollection *> *cameraRolls = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
        
    for (PHAssetCollection *collection in cameraRolls) {
        PHFetchResult<PHAsset *> *assets  =  [PHAsset fetchAssetsInAssetCollection:collection options:nil];
        for (PHAsset *phasset in assets) {
            if (phasset.mediaType == PHAssetMediaTypeVideo) {
                
                PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
                options.version = PHImageRequestOptionsVersionCurrent;
                options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
                           
                PHImageManager *manager = [PHImageManager defaultManager];
                [manager requestAVAssetForVideo:phasset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                    
               AVURLAsset *urlAsset = (AVURLAsset *)asset;
               NSURL *url = urlAsset.URL;
               DLog(@"%@",url);
               DLog(@"%@",[NSThread currentThread]);
                    
                VideoPlayModel * model = [[VideoPlayModel alloc] init];
                model.asset = phasset;
                model.url = url;
                [videoArray addObject:model];
                    
               }];
                
            }
        }
        
    }

    if ([Utilis isSimuLator]) {
        NSData *JSONData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Date" ofType:@"json"]];
       NSArray *array = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingAllowFragments error:nil];
       [array enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           VideoPlayModel *model = [VideoPlayModel new];
           [model setValuesForKeysWithDictionary:obj];
           [videoArray addObject:model];
       }];
    }
    
    return videoArray;

}
/**
 获取视频的 某每一帧
 @parampath 视频路径
 */
+ (void)getVideoImageWithVideoPath:(NSURL*)path successfulBlock:(void(^)(NSMutableArray * array))success_block{
    
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
    AVURLAsset *asset = [AVURLAsset URLAssetWithURL:path options:nil];
    NSInteger second = asset.duration.value/asset.duration.timescale;

    DLog(@"%ld",(long)second);
    
    NSMutableArray * array = NSMutableArray.array;
    
    if (second >= 30) {
        second = 30;
    }
    
    for (NSInteger i  = 1; i< second; i++) {
        UIImage * image = [Utilis getVideoImageWithTime:i videoPath:path];
        DLog(@"%@",image);
        [array addObject:image];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if (success_block) {
            success_block(array);
        }
    });
});
}
/**
 获取视频的 某一帧
 @paramcurrentTime 某一时刻单位 s
 @parampath 视频路径
 @returnreturn 返回image
 */
+ (UIImage*)getVideoImageWithTime:(Float64)currentTime videoPath:(NSURL*)path{

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];

    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];

    assetGen.appliesPreferredTrackTransform = YES;
//    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    CMTime time = CMTimeMakeWithSeconds(currentTime, 600);

    NSError*error =nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
    CGImageRelease(image);
    return videoImage;
}

@end
